package com.smart.manager.union.mall.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;

import com.smart.common.entities.option.SelectOption;
import com.smart.manager.union.mall.body.RUnionMallKind;
import com.smart.manager.union.mall.models.UnionMallKind;
import com.smart.manager.union.mall.models.query.QUnionMallKind;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 帮助中心
 *
 * @author leo
 * @date 2023/07/26
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class UnionMallKindRepository {

    /**
     * 查询搜索
     *
     * @param search 搜索
     * @return {@link Page}<{@link UnionMallKind}>
     */
    public Page<UnionMallKind> pageList(RUnionMallKind.SearchBody search) {
        QUnionMallKind query = new QUnionMallKind();
        Opt.ofBlankAble(search.getName()).ifPresent(x -> query.name.contains(x));
        Opt.ofBlankAble(search.getCode()).ifPresent(x -> query.code.contains(x));
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<UnionMallKind>().load(query.findPagedList());
    }

    /**
     * 添加
     *
     * @param body 身体
     */
    public void add(RUnionMallKind.EditBody body) {
        QUnionMallKind query = new QUnionMallKind();
        UnionMallKind record = query.code.eq(body.getCode()).setMaxRows(1).findOne();
        Assert.isNull(record, "创建失败:已存在相同的分类代码");
        BeanUtil.copyProperties(body, UnionMallKind.class).save();
    }

    /**
     * 更新
     *
     * @param id   id
     * @param body 身体
     */
    public void update(Long id, RUnionMallKind.EditBody body) {
        QUnionMallKind query = new QUnionMallKind();
        UnionMallKind record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();
    }

    /**
     * 删除ids
     *
     * @param ids id
     * @return int
     */
    public int delByIds(List<Long> ids) {
        List<UnionMallKind> list = new QUnionMallKind().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);
        for (UnionMallKind module : list) {
            log.warn("检查数据是否允许被删除  {}", module);
        }
        return DB.deleteAll(list);
    }

    /**
     * 获取数据字典
     */
    public List<SelectOption> getOptions() {
        return new QUnionMallKind().order().id.asc().findStream()
                .map(item -> new SelectOption().setLabel(item.getName()).setValue(item.getCode()))
                .collect(Collectors.toList());
    }
}
